import { Injectable } from '@nestjs/common';
import { CreatePoetryDto} from './dto';
import { Repository,In, Not, ReturnDocument } from 'typeorm';
import { InjectRepository} from '@nestjs/typeorm';
import {Poetry} from './entities/poetry.entity';
import { v4 as uuidv4 } from 'uuid';
import {ResultData} from '../../common/utils/result';
@Injectable()
export class PoetryService {
    constructor(
        @InjectRepository(Poetry)
        private poetryRepository: Repository<Poetry>,
      ) {}
    
    async create(poetry: CreatePoetryDto) {
        poetry.poetry_id = uuidv4();
        const res = await this.poetryRepository.insert(poetry)
        return ResultData.ok(res);
    }

    async createJson(data: CreatePoetryDto[]) {
        try {
          // 为每条记录生成唯一 ID 并序列化字段
          const processedData = data.map((item) => ({
            ...item,
            poetry_id: uuidv4(),
            tags: JSON.stringify(item.tags),
            paragraphs: JSON.stringify(item.paragraphs),
            biography:item.biography?item.biography:'',
            prologue:item.prologue?item.prologue:'',
            rhythmic:item.rhythmic?item.rhythmic:'',
            notes:item.notes?JSON.stringify(item.notes):"",
            type_name:"唐",
            type:'0',
          }));
      
          // 遍历数据逐条插入，捕获主键冲突错误
          for (const item of processedData) {
            try {
              await this.poetryRepository.insert(item); // 单条插入
            } catch (error) {
              // 检查是否为主键冲突错误
              if (error.code === 'ER_DUP_ENTRY') {
                console.warn(`Duplicate entry ignored for poetry_id: ${item.poetry_id}`);
                continue; // 忽略当前记录，继续下一条
              }
              throw error; // 如果是其他错误，则抛出
            }
          }
      
          return ResultData.ok();
        } catch (error) {
          return ResultData.fail(error.message || error);
        }
      }
      
    // async createJson(data:[]) {
    //     try {
    //         // 创建所有插入操作的 Promise
    //         const insertPromises = data.map(async (item:CreatePoetryDto) => {
    //             item.poetry_id = uuidv4();
    //             item.tags = JSON.stringify(item.tags);
    //             item.paragraphs = JSON.stringify(item.paragraphs);
    //             return await  this.poetryRepository.insert(item)  // 保存到数据库
    //         });
      
    //         // 等待所有插入操作完成
    //         await Promise.all(insertPromises);
      
    //         return ResultData.ok();
    //     } catch (error) {
    //         console.error('Error inserting data:', error);
    //         return ResultData.fail(error);
    //       }
    // }
}
